package view;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;

/**
 * MVC-like class structure
 * 
 */
public abstract class MVCComponent implements CommandListener {

	public static Display display;

	private MVCComponent callerView;

	protected abstract Displayable getScreen();

	protected abstract void initModel();

	protected abstract void createView();

	protected abstract void updateView();

	public abstract void commandAction(Command cmd, Displayable display);

	private Displayable prepareScreen() {
		if (getScreen() == null) {
			initModel();
			createView();
		} else {
			updateView();
		}
		getScreen().setCommandListener(this);
		return getScreen();
	}

	public void showScreen() {
		try {
			display.setCurrent(prepareScreen());
		} catch (Exception e) {
			Alert a = new Alert("Error in showing screen:\n"+e.getMessage());
			a.setTimeout(Alert.FOREVER);
			display.setCurrent(a);
		}
	}

	public void setCallerView(MVCComponent bv) {
		callerView = bv;
	}

	public MVCComponent getCallerView() {
		return callerView;
	}

	public void showCallerView() {
		if (callerView != null)
			callerView.showScreen();
	}

}